#!/bin/bash
set -xeuo pipefail
BASE_DIR=$(cd "$(dirname "$0")"; pwd)
cd ${BASE_DIR}

docker images |grep cypress-allinone ||(
 echo "没有Cyrpess定制的镜像文件"
 exit 1
)

if [ $(docker ps -a | grep cytest|wc -l) -eq "1" ]; then
 echo "start cytest"
 docker start cytest
else
 echo "run cytest"
 docker run -itd --name cytest -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY -v $PWD:/e2e --network host -w /e2e --entrypoint=cypress dev.docker:8085/cypress-allinone:6.1.0 open --project .
 
 sleep 5
 docker ps | grep cytest
fi

###如果需要清理当前项目的依赖，执行如下
# docker exec -it cytest bash -c "rm -rf /e2e/node_modules; rm -f /e2e/yarn.lock"

#如果需要更换npm源，打开下面这个
# https://registry.npm.taobao.org
docker exec -it cytest bash -c "npm config set registry https://registry.npm.taobao.org/; yarn config set registry https://registry.npm.taobao.org/"
# docker exec -it cytest bash -c "npm config set registry http://localhost:8083/repository/npm/; yarn config set registry http://localhost:8083/repository/npm/"

echo "安装必要的一些nodejs包"
echo "依赖包安装成功后，就可运行了^_^"
docker exec -it cytest bash -c "[ -d node_modules ] || yarn install --verbose  --use-yarnrc=/e2e/.yarnrc"
:<<EOF
如果cypress的版本差异，这步的时间会比较长，类似如下
该镜像的内置版本是 "cypress": "6.1.0",因此在package.json中要填写这个，不然会联网下载你指定的另外一个版本
Cypress安装慢的问题参考这个解决 https://www.cnblogs.com/mouseleo/p/11925437.html 
 https://npm.taobao.org/mirrors/cypress/ 这里可以下载安装包
 https://npm.taobao.org/mirrors?spm=a2c6h.14029880.0.0.2a2f75d7ssJWB1
 
[4/4] Building fresh packages...                                                           
verbose 53.170891775                                                                       
verbose 501.010965126 [03:36:05]  Downloading Cypress     [started]                        
[03:43:23]  Downloading Cypress     [completed]
[03:43:23]  Unzipping Cypress       [started]
[03:43:31]  Unzipping Cypress       [completed]
[03:43:31]  Finishing Installation  [started]
[03:43:31]  Finishing Installation  [completed]
EOF
#启动vscode环境 Enjoy code life!!!
docker exec -it cytest bash -c vscode

echo "此时依赖已经完备，ypress Runner出现的错误，此时刷新一下就好了"
:<<EOF
以后开始时执行这个脚本即可，同时启动cypress和vscode
以当前目录作为测试工程
EOF

echo "done"



